﻿using AutoMapper;
using MediatR;
using ZGLXM.ErrorCode;
using ZGLXM.Infra.Interface;
using ZGLXM.Infra.Repository;
using ZGLXM.Writh.Api.Applicantion.Command.RBAC;

namespace ZGLXM.Writh.Api.Applicantion.Handler.RBAC
{
    public class UserUpdateCommandHandler : IRequestHandler<UserUpdateCommand, ApiResult>
    {
        private readonly IUserRepository userRepository;
        private readonly IMapper mapper;
        private readonly ILogger<UserUpdateCommandHandler> logger;

        public UserUpdateCommandHandler(IUserRepository userRepository, IMapper mapper, ILogger<UserUpdateCommandHandler> logger)
        {
            this.userRepository = userRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult> Handle(UserUpdateCommand request, CancellationToken cancellationToken)
        {
            var user = await userRepository.GetAsync(x=>x.UserId == request.UserId);
            if (user == null)
            {
                return ApiResult.Fail("信息不存在");
            }
            var entity = mapper.Map(request, user);
            var res = await userRepository.UpdateAsync(entity);
            if (res > 0)
            {
                return ApiResult.OK("更新成功");
            }
            else
            {
                return ApiResult.Fail("更新失败");
            }
        }
    }
}
